

<template>

  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入要搜索的标签"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>


  <van-divider size="medium" content-position="left">已选标签</van-divider>

  <div v-if="activeIds.length === 0">暂无标签~</div>


  <van-row gutter="16">
    <van-col v-for="tag in activeIds">
      <van-tag  :show="show" closeable size="small" type="primary" @close="close(tag)" >
        {{tag}}
      </van-tag>
    </van-col>
  </van-row>


  <van-divider size="medium" content-position="left"/>


  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />


</template>


<script setup lang="ts">


import {ref, watch, watchEffect} from 'vue';
import { showToast } from 'vant';

const searchText = ref('');
const onSearch = (val) => {
  const newTagList = tagList.value.map(tag=>{
    const newChildren = tag.children.filter(c => c.text.includes(val));
    console.log(newChildren)
    if (newChildren.length > 0) {
      return {
        text: tag.text,
        children: newChildren
      }
    }
    return null;
  })
  tagList.value = newTagList.filter(newTag=> null !== newTag)
}

const onCancel = () => {
  searchText.value = '';
}

//选中的id数组
const activeIds = ref([]);



//左侧选中的索引（0，1，2）
const activeIndex = ref(0);

const tagListData = [
  {
    text: '浙江',
    children: [
      { text: '杭州', id: '杭州' },
      { text: '温州', id: '温州' },
      { text: '宁波', id: '宁波' },
      { text: '厦门', id: '厦门' },
      { text: '皮革厂', id: '皮革厂' },
    ],
  },
  {
    text: '江苏',
    children: [
      { text: '南京', id: '南京' },
      { text: '无锡', id: '无锡' },
      { text: '徐州', id: '徐州' },
    ],
  }
]
const tagList = ref(tagListData)

//移除标签
const close = (tag) => {
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag
  });
};


watch(searchText,(newVal,oldVal)=>{
  console.log("searchText旧值",oldVal);
  console.log("searchText新值",newVal);
  if ('' === newVal) {
    tagList.value = tagListData
  }
})




</script>

<style scoped>

</style>